package com.example.qrcodecamera;



import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCUtil {
    // 移除静态常量，改为动态构建
    private static final String DRIVER = "com.mysql.jdbc.Driver";

    public static Connection getNewConnection(String ip, String port, String user, String password) throws Exception {
        String url = buildConnectionUrl(ip, port);
        try {
            Class.forName(DRIVER);
            Connection conn = DriverManager.getConnection(url, user, password);
            if (!conn.isValid(2)) {
                throw new SQLException("连接有效性验证失败");
            }
            return conn;
        } catch (ClassNotFoundException e) {
            throw new Exception("驱动加载失败: " + DRIVER, e);
        } catch (SQLException e) {
            throw new Exception("连接失败: " + parseSqlException(e), e);
        }
    }

    private static String buildConnectionUrl(String ip, String port) {
        return "jdbc:mysql://" + ip + ":" + port + "/weight"
                + "?serverTimezone=GMT%2B8"
                + "&connectTimeout=5000"
                + "&socketTimeout=30000"
                + "&rewriteBatchedStatements=true"
                + "&useSSL=false";
    }

    // 统一错误解析（升级版）
    public static String parseSqlException(SQLException e) {
        String customMsg = getCustomErrorMessage(e.getErrorCode());
        return String.format("[%s] %s | 服务端消息: %s",
                e.getSQLState(), customMsg, e.getMessage());
    }

    private static String getCustomErrorMessage(int errorCode) {
        switch (errorCode) {
            case 1045:
                return "认证失败（用户:）";
            case 1049:
                return "数据库不存在 [weight]";
            case 2003:
                return "无法连接服务器";
            case 1062:
                return "数据重复（主键冲突）";
            case 3819:
                return "数据校验失败（值超出范围）";
            default:
                return "数据库错误 [" + errorCode + "]";
        }
    }
}

